package com.tgpms.web.element.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tgpms.common.Base64Util;
import com.tgpms.common.PageUtils;
import com.tgpms.common.Query;
import com.tgpms.util.FTPUtil;
import com.tgpms.web.element.dao.WsAcceptDao;
import com.tgpms.web.element.dao.WsDocDao;
import com.tgpms.web.element.dao.WsDocRelDao;
import com.tgpms.web.element.entity.WsAccept;
import com.tgpms.web.element.entity.WsDoc;
import com.tgpms.web.element.entity.WsDocRel;
import com.tgpms.web.element.service.WsAcceptService;
import com.tgpms.web.element.vo.WsDocVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service("wsAcceptService")
public class WsAcceptServiceImpl extends ServiceImpl<WsAcceptDao, WsAccept> implements WsAcceptService {
    @Autowired
    private WsDocDao wsDocDao;
    @Autowired
    private WsDocRelDao wsDocRelDao;
    @Value("${ftpparam.wzyslocalloadfile}")
    private String wzyslocalloadfile;
    @Value("${ftpparam.wzysdownloadtemppath}")
    private String wzysdownloadtemppath;
    //ftp_url
    @Value("${ftpparam.url}")
    private String url;
    @Value("${ftpparam.port}")
    private Integer port;
    @Value("${ftpparam.username}")
    private String username;
    @Value("${ftpparam.password}")
    private String password;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<WsAccept> page = this.page(
                new Query<WsAccept>().getPage(params),
                // 拼接查询条件
                new LambdaQueryWrapper<WsAccept>()
        );

        return new PageUtils(page);
    }

    @Override
    public PageUtils getAnnexById(String id, Map<String, Object> params) {
        // 查询附件关联表
        List<WsDocRel> wsDocRels = wsDocRelDao.selectList(new LambdaQueryWrapper<WsDocRel>().eq(WsDocRel::getDocRelId, id));
        // 获取附件id
        List<String> ids = wsDocRels.stream().map(WsDocRel::getId).collect(Collectors.toList());
        // 查询附件表
        IPage<WsDoc> page = wsDocDao.selectPage(new Query<WsDoc>().getPage(params), new LambdaQueryWrapper<WsDoc>().in(WsDoc::getId, ids));
        return new PageUtils(page);
    }

    @Override
    @Transactional
    public void removeWsAcceptByIds(List<String> ids) {
        if (this.removeByIds(ids)) {
            // 删除附件表
            List<WsDocRel> wsDocRels = wsDocRelDao.selectList(new LambdaQueryWrapper<WsDocRel>().in(WsDocRel::getDocRelId, ids));
            if (CollectionUtil.isNotEmpty(wsDocRels)) {
                List<String> idList = wsDocRels.stream().map(WsDocRel::getId).collect(Collectors.toList());
                wsDocRelDao.deleteBatchIds(idList);
                wsDocDao.deleteBatchIds(idList);
            }
        }
    }

    @Override
    public List<WsDocVo> getImgById(String id) {
        List<WsDocRel> wsDocRels = wsDocRelDao.selectList(new LambdaQueryWrapper<WsDocRel>().eq(WsDocRel::getDocRelId, id));
        if (CollectionUtil.isEmpty(wsDocRels)) {
            return new ArrayList<>();
        }

        List<String> idList = wsDocRels.stream().map(WsDocRel::getId).collect(Collectors.toList());
        List<WsDoc> wsDocs = wsDocDao.selectList(new LambdaQueryWrapper<WsDoc>().in(WsDoc::getId, idList));
        List<WsDoc> wsDocList = wsDocs.stream().filter(e -> {
            String extName = e.getExtName();
            return extName.equalsIgnoreCase("jpg") || extName.equalsIgnoreCase("png");
        }).collect(Collectors.toList());

        List<WsDocVo> wsDocVos = new ArrayList<>();
        for (WsDoc wsDoc : wsDocList) {
            WsDocVo wsDocVo = new WsDocVo();
            InputStream in = null;
            try {
                //先从本地文件夹取文件，有则本地下载，无则ftp下载
                String fileDir = wzyslocalloadfile;
                File dir = new File(fileDir);
                if (!dir.exists()) {
                    dir.mkdirs();
                    in = FTPUtil.downloadFileForIn(url, port, username, password, wsDoc.getFilePath(), wsDoc.getNewName());
                } else {
                    File excelFile = new File(dir.getAbsolutePath() + File.separator + wsDoc.getNewName());
                    if (excelFile.exists()) {
                        in = new FileInputStream(excelFile);
                    } else {
                        File temp = new File(wzysdownloadtemppath);
                        if (!temp.exists()) {
                            temp.mkdirs();
                        }
                        // 下载到本地,本地文件转成base64.定时任务删除临时下载文件
                        FTPUtil.downloadFile(url, port, username, password, wsDoc.getFilePath(), wsDoc.getNewName(), temp.getAbsolutePath());
                        File tempFile = new File(temp.getAbsolutePath() + File.separator + wsDoc.getNewName());
                        in = new FileInputStream(tempFile);
                    }
                }
                byte[] data = new byte[in.available()];
                in.read(data);
                String imageBase64Data = "data:image/png;base64," + Base64Util.ByteToBase64(data).replaceAll("\n|\r", "");
                wsDocVo.setId(wsDoc.getId());
                wsDocVo.setImages(imageBase64Data);
                wsDocVos.add(wsDocVo);
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                try {
                    if (in != null) {
                        in.close();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return wsDocVos;
    }


}